package com.wn.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.wn.common.constant.redis.RedisConstant;
import com.wn.common.exception.Assert;
import com.wn.common.result.enums.impl.BusinessCode;
import com.wn.sms.config.SmsTemplate;
import com.wn.sms.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @author yellow Docter
 * @date 2023 -07-21
 * @desc
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService, RedisConstant {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void send(String phone) {

        //01 从redis 中获取是否存在验证码  如果存在 不发送验证码
        String key = SMS_PREFIX + phone;
        String lock = SMS_PREFIX + phone + ":count";
        String code = stringRedisTemplate.opsForValue().get(key);
        boolean flag = StringUtils.isNotEmpty(code);

        //存在 抛出异常
        Assert.error(flag, BusinessCode.USER_VERIFY_CODE_EXEIT);
        //02 生成验证码
        String numbers = RandomUtil.randomNumbers(4);

        log.info("短信的验证码：====>{}",numbers);
        //短信的计数
        String count = stringRedisTemplate.opsForValue().get(lock);
        if ("3".equals(count)){
            Assert.error("不用短信轰炸。。。");
        }

        //03 存储redis中
        stringRedisTemplate.opsForValue().set(
                key,
                numbers,
                Duration.ofMinutes(30L)
        );

        if (StringUtils.isEmpty(count)){
            stringRedisTemplate.opsForValue().set(lock,"1",Duration.ofMinutes(10));
        }else{
            stringRedisTemplate.opsForValue().increment(lock);
        }

        //04 阿里云短信发送
        // smsTemplate.send(phone,numbers);

    }

}
